package com.open.capacity.form.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.CodeEnum;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.form.model.FormRelation;
import com.open.capacity.form.model.FormScheme;
import com.open.capacity.form.model.FormSchemeinfo;
import com.open.capacity.form.service.CustomerFormExtService;
import com.open.capacity.form.service.CustomerFormService;
import com.open.capacity.form.service.FormRelationService;
import com.open.capacity.form.vo.CustomerFormVo;
import com.open.capacity.form.vo.SchemeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 ftquan 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 表单
 */
@Slf4j
@RestController
@Api(tags = "表单信息模块api")
public class CustomerFormController {

    private ObjectMapper objectMapper = new ObjectMapper();


    @Autowired
    private CustomerFormService schemeService;

    @Autowired
    private CustomerFormExtService schemeExtService;

    @Autowired
    private FormRelationService formRelationService;

    /**
     * 查询表单
     *
     * @param params
     * @return
     */
    @PreAuthorize("hasAuthority('customerform:get/customerforms')")
    @ApiOperation(value = "查询表单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer")
    })
    @GetMapping("/customerforms")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public PageResult<FormSchemeinfo> pageSchemes(@RequestParam Map<String, Object> params) {
        return schemeService.pageSchemeinfos(params);
    }


    /**
     * 查询表单list
     *
     * @param parentId
     * @return
     */
    @PreAuthorize("hasAuthority('customerform:get/customerforms')")
    @ApiOperation(value = "查询表单list")
    @GetMapping("/customerforms/list")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result<List<FormSchemeinfo>> listSchemes(@RequestParam(value = "companyId") String companyId,
                                                    @RequestParam(value = "parentId", defaultValue = "0") String parentId,
                                                    @RequestParam(value = "keyword", required = false) String keyword) {
        Map<String, Object> params = new HashMap<>();
        params.put("companyId", companyId);
        params.put("parentId", parentId);
        params.put("keyword", keyword);
        List<FormSchemeinfo> list = schemeService.findSchemeinfos(params);
        return Result.succeed(list);
    }


    @ApiOperation(value = "获取表单")
    @PreAuthorize("hasAuthority('customerform:get/customerforms/{id}')")
    @GetMapping("/customerforms/{id}")
    public Result<SchemeVo> findSchemeById(@PathVariable(value = "id") String id) {
        SchemeVo schemeinfo = schemeService.findById(id);
        FormRelation relation = formRelationService.findByFormId(id);
        schemeinfo.setRelation(relation);
        return Result.succeed(schemeinfo);
    }


    @ApiOperation(value = "分页获取自定义表单数据")
    @PreAuthorize("hasAuthority('customerform:get/customerforms/{id}/getPreviewDatas')")
    @GetMapping("/customerforms/{id}/pagePreviewDatas")
    public PageResult<Map<String, Object>> pagePreviewDatas(@PathVariable(value = "id") String id,
                                                            Integer page,
                                                            Integer limit,
                                                            String queryJson) {
        try {
            Map<String, Object> queryMap = objectMapper.readValue(queryJson, Map.class);
            PageResult<Map<String, Object>> pageResult = schemeExtService.getFormPageList(id, page, limit, queryMap);
            return pageResult;
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return PageResult.<Map<String, Object>>builder().data(null).resp_code(CodeEnum.ERROR.getCode()).count((long) 0).build();
        }
    }

    @ApiOperation(value = "获取自定义表单数据")
    @PreAuthorize("hasAuthority('customerform:get/customerforms/{id}/getPreviewDatas')")
    @GetMapping("/customerforms/{id}/listPreviewDatas")
    public Result<List<Map<String, Object>>> listPreviewDatas(@PathVariable(value = "id") String id, String queryJson) {
        try {
            Map<String, Object> queryMap = objectMapper.readValue(queryJson, Map.class);
            List<Map<String, Object>> list = schemeExtService.getFormList(id, queryMap);
            return Result.succeed(list);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return Result.failed("系统繁忙");
        }
    }


    @ApiOperation(value = "获取自定义表单数据")
    @PreAuthorize("hasAuthority('customerform:get/customerforms/{id}/getInstanceForm')")
    @GetMapping("/customerforms/{id}/getInstanceForm")
    public Result<Map<String, List<Map<String, Object>>>> getInstanceForm(@PathVariable(value = "id") String id, String keyValue) {
        Map<String, List<Map<String, Object>>> formMap = schemeExtService.getInstanceForm(id, keyValue);
        return Result.succeed(formMap);
    }

    @ApiOperation(value = "保存自定义表单数据")
    @PreAuthorize("hasAuthority('customerform:post/customerforms/{id}/saveInstanceForm')")
    @PostMapping("/customerforms/{id}/saveInstanceForm")
    public Result<Map<String, List<Map<String, Object>>>> saveInstanceForm(@PathVariable(value = "id") String id, String processId, String keyValue, @RequestBody Map<String, Object> formData) {
        schemeExtService.saveInstanceForm(id, processId, keyValue, formData);
        return Result.succeed("操作成功！");
    }

    @PreAuthorize("hasAuthority('customerform:delete/customerforms/{id}/deleteInstanceForm')")
    @ApiOperation(value = "删除自定义表单数据")
    @DeleteMapping("/customerforms/{id}/deleteInstanceForm")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result deleteInstanceForm(@PathVariable(value = "id") String id, String keyValue) {
        try {
            schemeExtService.deleteInstanceForm(id, keyValue);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("操作失败");
        }
    }

    /**
     * 查询表单模板历史记录
     *
     * @param params
     * @return
     */
    @PreAuthorize("hasAuthority('customerform:get/customerforms')")
    @ApiOperation(value = "查询表单模板历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "schemeinfoId", value = "schemeinfoId", required = true, dataType = "String"),
            @ApiImplicitParam(name = "keyword", value = "关键字", dataType = "String")
    })
    @GetMapping("/customerforms/historySchemes")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public PageResult<FormScheme> pageHistorySchemes(@RequestParam Map<String, Object> params) {
        return schemeService.pageSchemes(params);
    }

    /**
     * 更新到历史模板
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('customerform:post/customerforms/{id}/updateScheme' )")
    @PostMapping(value = "/customerforms/{id}/updateScheme")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result updateScheme(@PathVariable(value = "id") String id, @RequestParam(value = "schemeId") String schemeId) {
        schemeService.updateScheme(id, schemeId);
        return Result.succeed(null, "更新成功");
    }

    /**
     * 更新表单状态
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('customerform:post/customerforms/{id}/updateStatus' )")
    @PostMapping(value = "/customerforms/{id}/updateStatus")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result updateStatus(@PathVariable(value = "id") String id, Integer status) {
        schemeService.updateStatus(id, status);
        return Result.succeed(null, "更新成功");
    }

    /**
     * 表单新增或者更新
     *
     * @param scheme
     * @return
     */
    @PreAuthorize("hasAnyAuthority('customerform:post/customerforms','customerform:put/customerforms')")
    @ApiOperation(value = "保存表单")
    @PostMapping("/customerforms/saveOrUpdate")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result saveOrUpdate(@RequestBody CustomerFormVo scheme) {
        return schemeService.saveOrUpdate(scheme);
    }


    /**
     * 删除
     * delete /customerforms/1
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('customerform:delete/customerforms/{id}')")
    @ApiOperation(value = "删除表单")
    @DeleteMapping("/customerforms/{id}")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result delete(@PathVariable(value = "id") String id) {
        try {
            schemeService.delete(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("操作失败");
        }
    }

}
